package main

import (
	"bufio"
	"fmt"
	"io"
	"strconv"

	"bytes"

	"github.com/hajimehoshi/oto"
)

var start bool
var otoCtx *oto.Context
var player *oto.Player

const bufferSize = 102400

func closePlayer() {
	player.Close()
}

func play(reader *io.PipeReader) {
	br := bufio.NewReader(reader)

	for {
		line1, err := br.ReadSlice('\n')
		if err != nil {
			break
		}
		if bytes.HasPrefix(line1, []byte("Icy-MetaData-Length:")) {
			wavHeaderLen, err := strconv.ParseInt(string(bytes.TrimSpace(line1[20:])), 10, 32)
			if err != nil {
				break
			}
			header := make([]byte, wavHeaderLen)
			//println("head length:", wavHeaderLen)
			n, _ := io.ReadFull(reader, header[:])
			if int64(n) != wavHeaderLen {
				return
			}
			if !start {
				samplesPerSec, channels, blockAlign := getWavInfo(header[:])
				fmt.Printf("samplesPerSec=%v\nchannels=%v\nblockAlign=%v\n", samplesPerSec, channels, blockAlign)
				otoCtx, err = oto.NewContext(samplesPerSec, channels, blockAlign/channels, samplesPerSec*blockAlign)
				if err != nil {
					panic(err)
				}
				defer otoCtx.Close()
				player = otoCtx.NewPlayer()
				defer player.Close()
				start = true
			}

		} else if bytes.HasPrefix(line1, []byte("SectionLength:")) {

			secLen, err := strconv.ParseInt(string(bytes.TrimSpace(line1[14:])), 10, 32)
			if err != nil {
				break
			}
			sec := make([]byte, secLen)
			n, _ := io.ReadFull(reader, sec[:])
			if int64(n) != secLen {
				return
			}

			if secLen >= 255 {
				player.Write(sec)
			}
		}
	}
	start = false
	println("player closed")
}
